package com.wqz.controller;

import com.wqz.pojo.blacklist;
import com.wqz.pojo.book;
import com.wqz.pojo.user;
import com.wqz.service.userServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private userServiceImpl userService;

    @RequestMapping("/tologin")
    public String tologin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, user user, Model model) {
        HttpSession session = request.getSession();
        String userName = user.getUserName();
        String password = user.getPassword();
        blacklist black = new blacklist();
        black.setUserName(userName);
        black.setPassword(password);
        boolean flag = userService.queryillegalUser(black);
        boolean login = userService.login(user);
        if (flag) {
            model.addAttribute("err", "您的账号为非法用户！");
            return "login";
        }
        if (login) {
            model.addAttribute("user", user);
            session.setAttribute("user", user);
            return "allBook";
        } else {
            session.setAttribute("error", "用户名或密码错误！");
            return "login";
        }

    }

    @RequestMapping("/toregister")
    public String toregister() {
        return "register";
    }


    @RequestMapping("/register")
    public String register(user user) {
        System.out.println(user);
        userService.addUser(user);
        return "login";
    }

    @RequestMapping("/queryUserByName/{bookName}")
    public String queryUserByName(@PathVariable("bookName") String bookName, Model model) {
        user users = userService.queryUserByName(bookName);
        List<user> list = new ArrayList<user>();
        list.add(users);

        if (users == null) {
            return "redirect:/book/empty";
        }
        model.addAttribute("users", users);
        return "queryUserByName";
    }

    @RequestMapping("/toUpdate/{userName}")
    public String toUpdate(@PathVariable("userName") String userName, Model model) {
        user users = userService.queryUserByName(userName);
        model.addAttribute("user", users);
        return "updateUser";
    }

    @RequestMapping("/updateUser")
    public String updateUser(user user, Model model) {
        userService.updateUser(user);
        user users = userService.queryUserByName(user.getUserName());
        model.addAttribute("user", users);
        return "allBook";
    }
}
